import React, { useEffect, useState } from 'react'
import { Button, Swiper, SwiperItem, View, CoverView, CoverImage } from '@tarojs/components'
import { checkJoinEnterprise, getCacheUserType, checkLogin } from '@/utils/user'
import { USER_TYPE } from '@/utils/enum/common'
import { getFullSrc, getFullSrcs, getNavTop } from '@/utils/Helper'
import Taro from '@tarojs/taro'
import { getMenuListWithoutLogin } from '@/services/xiaoxi'
import styles from './index.module.scss'
import { getEnterpriseList } from '@/services/company'

// nav 导航
export default function NavBarModal_yungu() {

  const [swiperFlag, setSwiperFlag] = useState(false);
  const [menuData, setMenuData] = useState(null);
  const [menuDataSize, setMenuDataSize] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const [showLoginModal, setShowLoginModal] = useState(false);
  const [indicatorDots, setIndicatorDots] = useState(false);
  const [enterpriseList, setEnterpriseList] = useState([]);

  const swiperChange = (e) => {
    const current = e.detail.current
    if (menuData.length - current * 8 > 4) {
      setSwiperFlag(true)
    } else {
      setSwiperFlag(true)
    }
  }

  // 报事报修
  const report = (url, title, menu_id) => {
    Taro.navigateTo({ url: url })
  }

  const getEnterpriseListFn = async () => {
    if (checkLogin()) {
      const resp = await getEnterpriseList()
      setEnterpriseList(resp || [])
    }
  }

  const goWxArticle = (url) => {
    Taro.openOfficialAccountArticle({
      url: url, // 此处填写公众号文章连接
      success: res => {
      },
      fail: res => {
      }
    })
  }

  // 修改地图导航处理函数
  const handleLocationNavigate = () => {
    // 使用山东未来云谷的经纬度
    const latitude = 36.6198749;
    const longitude = 117.064329;

    // 地点名称，可以帮助地图识别
    const name = "山东未来云谷";

    // 调用Taro的openLocation方法进行地图导航
    Taro.openLocation({
      latitude,  // 纬度
      longitude, // 经度
      name,      // 地点名称
      scale: 14   // 缩放级别，值越大，地图越详细
    });
  };



  // 菜单循环
  const menus = (size) => {
    return menuData?.map((item, index) => {
      let menuName = item.name;
      if (getCacheUserType() === USER_TYPE.STAFF && menuName === '员工管理') {
        menuName = '企业通讯录';
      }
      if (index >= size * 8 && index < (size + 1) * 8) {
        return (
          <CoverView
            className={styles.Exhibition}
            onClick={() => {
              if (item.menu_type === 2) {
                goWxArticle(item?.router);
              } else {
                // 如果是地图导航的菜单项
                if (item?.menu_id === 'c9l2ffag1hf8r4va2kg4') {
                  handleLocationNavigate(); // 调用地图导航功能
                } else {
                  if (
                    item?.menu_id === 'crbdo4upq9nionlcdvdg' || 
                    item?.menu_id === 'c9l2ffag1hf8r4va2kg2' ||
                    item?.menu_id === 'c9l2ffag1hf8r4va2kg7' ||
                    item?.menu_id === 'c9l2ffag1hf8r4va2kg4'
                  ) {
                    report(item?.router, item.name, item.menu_id);
                  } else {
                    if (!checkLogin()) {
                      // 用户未登录
                      setShowLoginModal(true);
                    } else {
                      const isJoin = enterpriseList.length > 0;
                      const excludedNames = ['云谷介绍', '入驻咨询', '地图导航','线上商城','我要投诉'];
                      if (isJoin || excludedNames.includes(menuName)) {
                        report(item?.router, item.name, item.menu_id);
                      } else {
                        setShowModal(!isJoin); // 仅当未加入企业且菜单名称不在排除列表时调用
                      }
                    }
                  }
                }
              }
            }}
          >
            <CoverImage className={styles.photo} src={getFullSrc(item?.icon)}></CoverImage>
            <CoverView className={styles.words}>{menuName}</CoverView>
          </CoverView>
        )
      }
    })
  }


  const goSearchCompany = () => {
    setShowModal(false)
    Taro.navigateTo({ url: '/pages/search-company/index' })
  }

  // 获取菜单列表
  const menuList = () => {
    // 使用内嵌数据，移除接口请求部分
    const menuData = [
      {
        hidden: 0,
        icon: getFullSrcs('documents/ygjs.png'),
        is_completed: 2,
        menu_id: "c9l2ffag1hf8r4va2kg2",
        name: "云谷介绍",
        parent_id: "c9l27nag1hf8r4va2k80",
        parent_path: "c9f6n42g1hfbekqmc6ag/c9l27nag1hf8r4va2k80",
        router: "/pages/home-new-con/yghc/index",
        sequence: 8000000,
        title: "云谷介绍",
        visible: 2,
      },
      {
        hidden: 0,
        icon: getFullSrcs('documents/rzzx.png'),
        is_completed: 2,
        menu_id: "c9l2ffag1hf8r4va2kg3",
        name: "入驻咨询",
        parent_id: "c9l27nag1hf8r4va2k80",
        parent_path: "c9f6n42g1hfbekqmc6ag/c9l27nag1hf8r4va2k80",
        router: "/pages/home-new-con/link/index",
        sequence: 8000000,
        title: "入驻咨询",
        visible: 2,
      },
      {
        hidden: 0,
        icon: getFullSrcs('documents/dtdh.png'),
        is_completed: 2,
        menu_id: "c9l2ffag1hf8r4va2kg4",
        name: "地图导航",
        parent_id: "c9l27nag1hf8r4va2k80",
        parent_path: "c9f6n42g1hfbekqmc6ag/c9l27nag1hf8r4va2k80",
        router: "",
        sequence: 8000000,
        title: "地图导航",
        visible: 2,
      },
      {
        hidden: 0,
        icon: getFullSrcs('documents/syxssc.png'),
        is_completed: 2,
        menu_id: "c9l2ffag1hf8r4va2kg5",
        name: "线上商城",
        parent_id: "c9l27nag1hf8r4va2k80",
        parent_path: "c9f6n42g1hfbekqmc6ag/c9l27nag1hf8r4va2k80",
        router: "/pages/shop/index",
        sequence: 8000000,
        title: "线上商城",
        visible: 2,
      },
      // {
      //   hidden: 0,
      //   icon: getFullSrcs('documents/ts.jpg'),
      //   is_completed: 2,
      //   menu_id: "c9l2ffag1hf8r4va2kg6",
      //   name: "我要投诉",
      //   parent_id: "c9l27nag1hf8r4va2k80",
      //   parent_path: "c9f6n42g1hfbekqmc6ag/c9l27nag1hf8r4va2k80",
      //   router: "/pages/repair-detail/index?type=4",
      //   sequence: 8000000,
      //   title: "我要投诉",
      //   visible: 2,
      // },
      {
        hidden: 0,
        icon: "http://182.45.184.174:10001/talent/files/0de25e45-4551-46a3-8aa4-e8cb4598253a/%E9%80%8F%E6%98%8E.png",
        is_completed: 2,
        menu_id: "c9l2ffag1hf8r4va2kg7",
        name: "",
        parent_id: "c9l27nag1hf8r4va2k80",
        parent_path: "c9f6n42g1hfbekqmc6ag/c9l27nag1hf8r4va2k80",
        router: "/pages/page-empty/index",
        sequence: 8000000,
        title: "",
        visible: 2,
      },

    ];

    const arr = [];
    const num = menuData.length / 8;

    for (let i = 0; i < num; i++) {
      arr.push(i);
    }

    // 根据计算的菜单数量判断是否显示分页指示器
    if (arr.length > 1) {
      setIndicatorDots(true);
    }

    // 根据菜单数量决定是否显示 swiper
    if (menuData.length <= 4) {
      setSwiperFlag(false);
    } else {
      setSwiperFlag(true);
    }

    // 更新菜单数据和分页数据
    setMenuData(menuData);
    setMenuDataSize(arr);
  };

  // 使用 useEffect 初始化菜单数据
  useEffect(() => {
    menuList();
    getEnterpriseListFn();  // 如果该函数依然需要调用
  }, []);

  return (
    <View>
      <CoverView className={styles.navBarModal} style={{ top: `${getNavTop()}px` }}>
        {/*轮播*/}
        <CoverView className={styles.banner}>
          <CoverView className={styles.bord}>
            <Swiper
              className={swiperFlag ? `${styles.swiper}` : `${styles.noSwiper}`}
              indicatorColor='#E7E5E8'
              indicatorActiveColor='#1B69FD'
              indicatorDots={indicatorDots}
              onChange={(e) => swiperChange(e)}
            >
              {menuDataSize?.map((size) => {
                return (
                  <SwiperItem className={styles.swiperImgContent} key={size}>
                    <CoverView className={styles.choice}>{menus(size)}</CoverView>
                  </SwiperItem>
                )
              })}
            </Swiper>
          </CoverView>
        </CoverView>
      </CoverView>
      {showLoginModal ? <CoverView className={styles.modal}>
        <CoverView className={styles.modalCon}>
          <CoverView className={styles.modalHeader}>提示</CoverView>
          <CoverView className={styles.modalContent}>请在登录后使用此功能</CoverView>
          <CoverView className={styles.modalButton}>
            <Button onClick={() => {
              setShowLoginModal(false)
              Taro.navigateTo({ url: '/pages/login/index' })
            }}>确定</Button>
          </CoverView>
        </CoverView>
      </CoverView> : null}

      {showModal ? <CoverView className={styles.modal}>
        <CoverView className={styles.modalCon}>
          <CoverView className={styles.modalHeader}>提示</CoverView>
          <CoverView className={styles.modalContent}>您还没有加入企业，请咨询企业管理员加入企业</CoverView>
          <CoverView className={styles.modalButton}>
            <Button onClick={() => {
              setShowModal(false)
              Taro.navigateTo({ url: '/pages/search-company/index' })
            }}>确定</Button>
          </CoverView>
        </CoverView>

      </CoverView> : null}
    </View>
  )
}
